package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是HandlerMethod就直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取访问的处理方法
        HandlerMethod method = (HandlerMethod) handler;
        //拿注解
        RequiredPermission ano = method.getMethodAnnotation(RequiredPermission.class);
        //判断注解是否为空
        if (ano == null) {
            return true;
        }
        //获取用户信息
        Employee employee = (Employee)request.getSession().getAttribute("USER_IN_SESSION");
        //判断是否为管理员
        if (employee.isAdmin()) {
            return true;
        }
        //查询用户的权限集合
        List<String> expressions = (List<String>) UserContext.getExpressions();
        //获取注解中的权限表达式
        String expression = ano.expression();
        //判断权限表达式是否在集合中
        if (expressions.contains(expression)) {
            return true;
        }
        response.sendRedirect("/noPermission");
        return false;
    }
}
